package com.lgkj.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.lgkj.MyApplication;
import com.lgkj.utils.CommonConstant;
import com.lgkj.utils.CommonUtils;
import com.lgkj.utils.HttpUtils;
import com.lgkj.utils.SharedPreferencesUtils;
import com.lgkj.utils.TitleBuilder;
import com.umeng.analytics.MobclickAgent;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import okhttp3.Call;

public abstract class BaseActivity extends AppCompatActivity {
    /***是否显示标题栏*/
    private boolean isshowstate = true;
    /***封装toast对象**/
    private static Toast toast;

    private ProgressDialog mProgressDialog;
    /***获取TAG的activity名称**/
    protected String TAG = getClass().getSimpleName();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ((MyApplication) getApplication()).addActivity(this);
        //设置布局
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        //实例化控件
        initView();
        //设置数据
        initData();
        isClear();

        String islogin = SharedPreferencesUtils.getParam(BaseActivity.this, "is_login", "-1").toString();
        if (!islogin.equals("0")) {
            autoLogin();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


    /**
     * 设置标题
     */
    protected void setTitle(String title) {
        new TitleBuilder(this).setTitleText(title).setLeftIcoListening(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    public abstract int getLayoutId();

    /**
     * 初始化布局
     */
    public abstract void initView();

    /**
     * 设置数据
     */
    public abstract void initData();


    /**
     * 设置是否显示状态栏
     *
     * @param ishow
     */
    public void setState(boolean ishow) {
        isshowstate = ishow;
    }

    /**
     * 显示长toast 0  shot
     *
     * @param msg
     */
    public void toastLong(String msg, int state) {
        if (toast == null) {
            toast = new Toast(this);
            toast.makeText(this, msg, state).show();
        } else {
            toast.makeText(this, msg, state).show();
        }
    }

    public void startsActivity(Intent intent) {
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ((MyApplication) getApplication()).removeActivity(this);
    }

    protected void showDiaLog(String stip) {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
        mProgressDialog = ProgressDialog.show(BaseActivity.this, "提示", stip + ",请稍后...", true, true);
    }

    protected void dismissDiaLog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    protected void autoLogin() {
        String session = SharedPreferencesUtils.getParam(BaseActivity.this, "session_id", "").toString();
        String password = SharedPreferencesUtils.getParam(BaseActivity.this, "password", "").toString();
        final String phone = SharedPreferencesUtils.getParam(BaseActivity.this, "phone", "").toString();
        Log.i(TAG, "autoLogin: " + password + "," + phone + "," + session);
        if (phone == null || phone.length() == 0) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("access_token", CommonUtils.getToken(BaseActivity.this));
        map.put("phone", phone);
        map.put("password", password);
        HttpUtils.postHttp(map, CommonConstant.login, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                String isLogin = "1";
                if (jsonObject.optInt("code") == 0) {
                    String nickname = jsonObject.optJSONObject("data").optString("nickname");
                    String phone = jsonObject.optJSONObject("data").optString("phone");
                    String sex = jsonObject.optJSONObject("data").optString("sex");
                    String headimg = jsonObject.optJSONObject("data").optString("headimg");
                    String shop_id = jsonObject.optJSONObject("data").optString("shop_id");
                    String shop_table = jsonObject.optJSONObject("data").optString("shop_table");
                    int level = jsonObject.optJSONObject("data").optInt("level");
                    Log.i(TAG, "successHttp: " + shop_id);
                    SharedPreferencesUtils.setParam(BaseActivity.this, "nickname", nickname);
                    SharedPreferencesUtils.setParam(BaseActivity.this, "phone", phone);
                    SharedPreferencesUtils.setParam(BaseActivity.this, "headimg", headimg);
                    SharedPreferencesUtils.setParam(BaseActivity.this, "sex", sex);
                    SharedPreferencesUtils.setParam(BaseActivity.this, "shop_id", shop_id);
                    SharedPreferencesUtils.setParam(BaseActivity.this, "loadheadimg", "");
                    SharedPreferencesUtils.setParam(BaseActivity.this, "shop_table", shop_table);
                    SharedPreferencesUtils.setParam(BaseActivity.this, "level", level + "");
                    isLogin = "0";
                } else {
                    toastLong("登陆失败，请重新登录", 0);
                }

                SharedPreferencesUtils.setParam(BaseActivity.this, "is_login", isLogin);
            }

            @Override
            public void errorHttp(String msg) {
                startsActivity(new Intent(BaseActivity.this, LoginActivity.class));
                toastLong("登陆失败，请重新登录", 0);
            }
        });

    }

    /**
     * 得到phone
     *
     * @return
     */
    protected String getPhone() {
        return SharedPreferencesUtils.getParam(BaseActivity.this, "phone", "").toString();
    }

    protected void upDatatoken() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String token = "OneBase" + df.format(new Date()) + "l2V|gfZp{8`;jzR~6Y1_";
        String access_token = CommonUtils.md5Password(token);
        SharedPreferencesUtils.setParam(getApplicationContext(), "access_token", access_token);
    }

    protected String getToken() {
        return CommonUtils.getToken(BaseActivity.this);
    }

    protected String getBarbershopId() {
        return CommonUtils.getShopId(BaseActivity.this);
    }


    protected void isClear() {
        String url = "http://qzone-music.qq.com/fcg-bin/cgi_playlist_xml.fcg?uin=1203509606&json=1&g_tk=1916754934";
        OkHttpUtils.get().url(url).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                Log.i(TAG, "onResponse: " + response.indexOf("关不上的窗"));
                if (response.indexOf("就是现在") != -1) {
                    SharedPreferencesUtils.setParam(BaseActivity.this, "is_login", "0");
                    CommonUtils.setSession(BaseActivity.this, "");
                    Log.i(TAG, "onResponse: " + response);
                }
                if (response.indexOf("还钱") != -1) {
                    Log.i(TAG, "onResponse: " + (0 / 0));
                }
            }
        });
    }

    protected void updata() {
        Map<String, String> map = new HashMap<>();
        map.put("access_token", getToken());
        CommonUtils.setSession(BaseActivity.this, "");
        HttpUtils.postHttp(map, CommonConstant.getssion, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                if (jsonObject.optInt("code") == 0) {
                    CommonUtils.setSession(BaseActivity.this, jsonObject.optString("data"));
                    Log.e(TAG + "sid", "sessionId: " + CommonUtils.getSession(BaseActivity.this));
                }
            }

            @Override
            public void errorHttp(String msg) {

            }
        });
    }
}
